package com.example.osstest.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import com.example.osstest.service.FileUploadService;
import com.example.osstest.vo.FileUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("oss")
public class FileUploadController {
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * @desc 文件上传到oss
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @RequestMapping("upload")
    public FileUploadResult[] upload(@RequestParam("file")MultipartFile[] uploadFile)
        throws Exception{
        return this.fileUploadService.upload(uploadFile);
    }

    /**
     * @desc 根据文件名删除oss上的文件
     * @param objectName
     * @return
     * @throws Exception
     */
    @RequestMapping("delete")
    public FileUploadResult delete(@RequestParam("fileName")String objectName)
        throws Exception{
        return this.fileUploadService.delete(objectName);
    }

    /**
     * @desc 查询oss上的所有文件
     * @return
     * @throws Exception
     */
    @RequestMapping("list")
    public List<OSSObjectSummary> list() throws Exception{
        return this.fileUploadService.list();
    }

    /**
     * @desc 根据文件名下载oss上的文件
     * @param objectName
     * @param response
     * @throws IOException
     */
    @RequestMapping("download")
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        this.fileUploadService.exportOssFile(response.getOutputStream(),objectName);
    }

}
